<script setup lang="ts" name="HistoryCleanup">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { isHistoryCleanup, getHistoryTimeToLiveValue, setHistoryTimeToLiveValue } from '../../utils/historyCleanup'
import EventEmitter from '@/utils/EventEmitter'

const historyTimeToLive = ref('')

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const getElementHistoryTimeToLiveValue = () => {
  historyTimeToLive.value = getHistoryTimeToLiveValue(mapStates.value.getActive()) === undefined ? '' : getHistoryTimeToLiveValue(mapStates.value.getActive())
}
const setElementHistoryTimeToLiveValue = (value: string | undefined) => {
  setHistoryTimeToLiveValue(mapStates.value.getActive(), value)
}

const eventEmitterListener = () => {
  if (isHistoryCleanup(mapStates.value.getActive())) {
    getElementHistoryTimeToLiveValue()
  }
}

onBeforeUnmount(() => {
  EventEmitter.removeListener('element-update', eventEmitterListener)
})

onMounted(() => {
  getElementHistoryTimeToLiveValue()
  EventEmitter.on('element-update', eventEmitterListener)
})
</script>

<template>
  <el-collapse-item name="history-cleanup">
    <template #title>
      <div class="collapse-header">
        <svg-icon icon="ri:time-fill"></svg-icon>
        <h2>数据缓存</h2>
      </div>
    </template>
    <el-form-item label="缓存时间">
      <el-input v-model="historyTimeToLive" maxlength="32" @change="setElementHistoryTimeToLiveValue" />
    </el-form-item>
  </el-collapse-item>
</template>

<style scoped lang="scss">
.el-collapse-item {
  :deep(.el-collapse-item__header) {

    .collapse-header {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 12px;

      .el-icon {
        margin-right: 6px;
        font-size: 20px !important;
      }

      h2 {
        font-weight: bold;
        font-size: 14px;
      }

      .el-button {
        margin-left: 12px;
      }
    }

    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-collapse-item__content) {
    padding-right: 12px;
    padding-bottom: 12px;
    padding-left: 12px;
  }
}

.el-form-item {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;

    .el-button.add {
      width: 100%;
      margin: 12px 0 0;
    }
  }
}
</style>
